package com.redijedi.tapestry.internal;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author torr
 * 
 */
public class InternalUtils {

	/**
	 * Converts an array of type String into a Map of String types. Every
	 * sequential pair will become key-value pairs in the Map returned.
	 * 
	 * @param strings
	 * @return
	 */
	public static Map<String, String> mapFromKeysAndValues(String... strings) {
		Map<String, String> map = new HashMap<String, String>();

		for (int i = 0; i < strings.length;) {
			if (strings.length >= i + 2) {
				map.put(strings[i], strings[++i]);
			} else {
				map.put(strings[i++], "");
			}
		}

		return map;
	}

	/**
	 * Converts a string to a valid identifier string. This includes removing
	 * invalid characters.
	 * 
	 * @param s
	 *            The String to convert to an identifier.
	 * @return The converted String.
	 */
	public static String convertStringToIdentifier(String s) {
		return s.replace(" ", "");
	}

	public static String convertValueToString(Object value) {
		if (value instanceof String) {
			return (String) value;
		} else if (value instanceof Integer) {
			return String.valueOf((Integer) value);
		}
		if (value instanceof Long) {
			return String.valueOf((Long) value);
		}
		if (value instanceof Double) {
			return String.valueOf((Double) value);
		} else {
			return null;
		}
	}

	public static Double convertValueToDouble(Object value) {
		if (value instanceof String) {
			return Double.valueOf((String) value);
		} else if (value instanceof Integer) {
			return Double.valueOf(String.valueOf((Integer) value));
		}
		if (value instanceof Long) {
			return Double.valueOf(String.valueOf((Long) value));
		}
		if (value instanceof Double) {
			return (Double) value;
		} else {
			return null;
		}
	}

	/**
	 * Converts a list of comma separated values into a java.util.List of
	 * Strings.
	 * 
	 * @param list
	 * @return
	 */
	public static List<String> convertStringToListOfStrings(String list) {
		List<String> newList = new ArrayList<String>();
		if (list != null) {
			String[] splitList = list.split(",");
			for (String s : splitList) {
				newList.add(s);
			}
		}
		return newList;
	}

	/**
	 * Converts an array of objects into a java.util.List of
	 * Strings.
	 * 
	 * @param list
	 * @return
	 */
	public static List<Object> convertArrayToListOfObjects(Object[] list) {
		List<Object> newList = new ArrayList<Object>();
		if (list != null) {
			for (Object o : list) {
				newList.add(o);
			}
		}
		return newList;
	}

}
